/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frame.HangHoa;

import dao.DonViDAO;
import pojo.Donvi;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.SessionException;

/**
 *
 * @author Quan
 */
public class QLDonVi extends javax.swing.JDialog {

    private DefaultTableModel tablemodel;

    /**
     * Creates new form QLDonVi
     */
    public QLDonVi() {
        initComponents();
        this.tablemodel = new DefaultTableModel();
        tablemodel.addColumn("ID");
        tablemodel.addColumn("Ký Hiệu");
        tablemodel.addColumn("Tên Đơn Vị");
        tablemodel.addColumn("Ghi Chú");
        this.masterTable.setModel(this.tablemodel);
        this.masterTable.setAutoCreateRowSorter(true);
        LoadData();
    }

    private void LoadData() {
        tablemodel.getDataVector().removeAllElements();
        List<Donvi> ds = null;
        try {
            ds = dao.DonViDAO.LayDanhSachDonVi();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e.getMessage(), "Thông báo", JOptionPane.ERROR_MESSAGE);
        }
        if (ds != null) {
            for (int i = 0; i < ds.size(); i++) {
                Donvi dv = ds.get(i);
                this.tablemodel.addRow(new Object[]{
                            dv.getId(),
                            dv.getKyhieu(),
                            dv.getTendonvi(),
                            dv.getGhichu()
                        });
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        idLabel = new javax.swing.JLabel();
        kyHieuLabel = new javax.swing.JLabel();
        tenDonViLabel = new javax.swing.JLabel();
        ghiChuLabel = new javax.swing.JLabel();
        idField = new javax.swing.JTextField();
        kyHieuField = new javax.swing.JTextField();
        tenDonViField = new javax.swing.JTextField();
        ghiChuField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Quản lý đơn vị");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        idLabel.setText("ID");

        kyHieuLabel.setText("Ký Hiệu");

        tenDonViLabel.setText("Tên Đơn Vị");

        ghiChuLabel.setText("Ghi Chú");

        idField.setEditable(false);

        saveButton.setText("Sửa");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        refreshButton.setText("Đóng");
        refreshButton.setActionCommand("");
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        newButton.setText("Thêm mới");
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Xóa");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        masterTable.setAutoCreateRowSorter(true);
        masterTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        masterTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                masterTableMouseClicked(evt);
            }
        });
        masterTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                masterTableKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(masterTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 148, Short.MAX_VALUE)
                        .addComponent(newButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(refreshButton))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(idLabel)
                            .addComponent(kyHieuLabel)
                            .addComponent(tenDonViLabel)
                            .addComponent(ghiChuLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(idField)
                            .addComponent(kyHieuField)
                            .addComponent(tenDonViField)
                            .addComponent(ghiChuField))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(idLabel)
                    .addComponent(idField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(kyHieuLabel)
                    .addComponent(kyHieuField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tenDonViLabel)
                    .addComponent(tenDonViField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ghiChuLabel)
                    .addComponent(ghiChuField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(refreshButton)
                    .addComponent(newButton)
                    .addComponent(deleteButton))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        long id = Long.parseLong(idField.getText());

        if (id > 0) {
            Donvi dv = new Donvi();
            dv.setId(id);
            dv.setKyhieu(kyHieuField.getText());
            dv.setTendonvi(tenDonViField.getText());
            dv.setGhichu(ghiChuField.getText());
            DonViDAO dvdao = new DonViDAO();
            try {
                dvdao.Sua(dv);
                LoadData();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, e.getMessage(), "Thông báo", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        Donvi dv = new Donvi();
        dv.setKyhieu(kyHieuField.getText());
        dv.setTendonvi(tenDonViField.getText());
        dv.setGhichu(ghiChuField.getText());
        DonViDAO dvdao = new DonViDAO();
        try {
            dvdao.Them(dv);
            LoadData();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Thông báo", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(QLDonVi.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_newButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        long id = -1;
        try {
            id = Long.parseLong(idField.getText());
        } catch (NumberFormatException e) {
            System.out.println("Chưa chọn.");
        } catch (Exception e) {
            System.out.println("Lỗi chưa xác định.");
        }

        if (id >= 0) {
            Donvi dv = new Donvi();
            dv.setId(id);
            DonViDAO dvdao = new DonViDAO();
            try {
                dvdao.Xoa(dv);
                LoadData();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Thông báo", JOptionPane.ERROR_MESSAGE);
                Logger.getLogger(QLDonVi.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_deleteButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        // TODO add your handling code here:
        Donvi dv = new Donvi();
        int i = masterTable.getSelectedRow();
        if (i != -1) {
            idField.setText(masterTable.getValueAt(i, 0).toString());
            kyHieuField.setText(masterTable.getValueAt(i, 1).toString());
            tenDonViField.setText(masterTable.getValueAt(i, 2).toString());
            ghiChuField.setText(masterTable.getValueAt(i, 3).toString());
        }
    }//GEN-LAST:event_masterTableMouseClicked

    private void masterTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_masterTableKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_masterTableKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QLDonVi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new QLDonVi().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteButton;
    private javax.swing.JTextField ghiChuField;
    private javax.swing.JLabel ghiChuLabel;
    private javax.swing.JTextField idField;
    private javax.swing.JLabel idLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField kyHieuField;
    private javax.swing.JLabel kyHieuLabel;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField tenDonViField;
    private javax.swing.JLabel tenDonViLabel;
    // End of variables declaration//GEN-END:variables
}
